package com.shanlitech.et;

import com.google.protobuf.Descriptors;
import com.shanlitech.et.pb.Agpub;
import com.shanlitech.et.utils.FastUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zeromq.ZContext;
import org.zeromq.ZMQ;
import org.zeromq.ZMQ.Socket;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

//声明一个autoRun类，使用服务器后台监听接口。固定用法，死记硬背
@WebListener
public class App implements ServletContextListener{
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	public SpeechRecorder recorder=null;

    //当后台被初始化，即发生了tomcat启动了事件，固定用法
    public void contextInitialized(ServletContextEvent arg0){
    	   	
    //你要做的事儿，写在这里
    	SpeechRecorder.getInstance().start();

        logger.info("MainFunction is running.");
		logger.info("配置文件地址:" + FastUtils.conf_filename);
		logger.info("nginx地址:" + FastUtils.nginx_url);

        /*String configPath = null;
		File root = new File(arg0.getServletContext().getRealPath("/"));
		if(root.isDirectory()) {
			configPath = root.getParent();
		}
		configFile = configPath +  "/config.properties";
		System.out.println("configPath: " + configFile);*/
    }
    //当后台被销毁，即发生了tomcat关闭了事件，固定用法
    public void contextDestroyed(ServletContextEvent arg0){
        //执行内容写在这里
    	SpeechRecorder.getInstance().stop();
    	logger.info("stop..........");
    	
    	
    	
    }
    
    private static void test() {
		ZContext ctx = new ZContext();

		Socket sub = ctx.createSocket(ZMQ.SUB);
		boolean ret=sub.connect("tcp://192.168.1.4:8893");
		
		sub.subscribe(ZMQ.SUBSCRIPTION_ALL);

		ZProtobuf zpb = new ZProtobuf(Agpub.getDescriptor());


		while(true) {
			ZProtobuf.RecvStruct pkg;
			pkg = zpb.recv(sub,true);
			if( pkg != null ) {
				Descriptors.Descriptor md = pkg.msg.getDescriptorForType();
				System.out.println( "recv pub message: " + md.getFullName());

				if( md.equals(Agpub.MemberGotMic.getDescriptor()) ) {
					System.out.println( "MemberGotMic " );
				} else if( md.equals(Agpub.MemberLostMic.getDescriptor()) ) {
					System.out.println( "MemberLostMic " );
				} else if( md.equals(Agpub.AudioPacket.getDescriptor()) ) {
					System.out.println( "AudioPacket" );
				}
			} else {
				System.out.println("fail to recv pkg");
			}
		}
	}
}
